import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:fl_chart/fl_chart.dart';
import '../constants/app_colors.dart';
import '../providers/mood_provider.dart';
import '../utils/date_util.dart';
import '../widgets/mood_chart.dart';
import 'package:google_fonts/google_fonts.dart';

class StatsScreen extends StatefulWidget {
  const StatsScreen({Key? key}) : super(key: key);

  @override
  State<StatsScreen> createState() => _StatsScreenState();
}

class _StatsScreenState extends State<StatsScreen> {
  String _selectedPeriod = '周';
  
  @override
  void initState() {
    super.initState();
    // 初始加载数据
    _loadData();
  }
  
  Future<void> _loadData() async {
    final moodProvider = context.read<MoodProvider>();
    String startDate;
    
    switch (_selectedPeriod) {
      case '周':
        startDate = DateUtil.getStartOfWeek();
        break;
      case '月':
        startDate = DateUtil.getStartOfMonth();
        break;
      case '年':
        startDate = DateUtil.getOneMonthAgo();
        break;
      default:
        startDate = DateUtil.getOneWeekAgo();
    }
    
    await moodProvider.loadMoodHistory(
      startDate: startDate,
      endDate: DateUtil.getCurrentDate(),
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        centerTitle: true,
        title: Text(
          '情绪统计',
          style: GoogleFonts.zcoolKuaiLe(
            fontSize: 24,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: Consumer<MoodProvider>(
        builder: (context, moodProvider, child) {
          if (moodProvider.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          
          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 时间段选择
                _buildPeriodSelector(),
                const SizedBox(height: 24),
                
                // 情绪趋势图
                MoodChart(
                  moods: moodProvider.moodHistory,
                  title: '情绪趋势',
                  days: _selectedPeriod == '周' ? 7 : 30,
                ),
                const SizedBox(height: 32),
                
                // 情绪分布饼图
                _buildMoodDistribution(moodProvider),
              ],
            ),
          );
        },
      ),
    );
  }
  
  Widget _buildPeriodSelector() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        _buildPeriodButton('周'),
        _buildPeriodButton('月'),
        _buildPeriodButton('年'),
      ],
    );
  }
  
  Widget _buildPeriodButton(String period) {
    final isSelected = _selectedPeriod == period;
    
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8),
      child: ElevatedButton(
        onPressed: () {
          setState(() {
            _selectedPeriod = period;
          });
          _loadData();
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: isSelected ? AppColors.primary : Colors.white,
          foregroundColor: isSelected ? Colors.white : AppColors.textPrimary,
          elevation: isSelected ? 2 : 0,
          side: BorderSide(
            color: isSelected ? AppColors.primary : Colors.grey.shade300,
          ),
        ),
        child: Text(period),
      ),
    );
  }
  
  Widget _buildMoodDistribution(MoodProvider moodProvider) {
    // 计算情绪分布
    final moodCounts = <int, int>{};
    for (var mood in moodProvider.moodHistory) {
      moodCounts[mood.moodType] = (moodCounts[mood.moodType] ?? 0) + 1;
    }
    
    // 如果没有数据，显示空状态
    if (moodCounts.isEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '情绪分布',
            style: Theme.of(context).textTheme.titleLarge,
          ),
          const SizedBox(height: 16),
          SizedBox(
            height: 200,
            child: Center(
              child: Text(
                '暂无数据',
                style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                  color: AppColors.textSecondary,
                ),
              ),
            ),
          ),
        ],
      );
    }
    
    // 准备饼图数据
    final pieChartSections = moodCounts.entries.map((entry) {
      final moodType = entry.key;
      final count = entry.value;
      final color = AppColors.getMoodColor(moodType);
      
      return PieChartSectionData(
        color: color,
        value: count.toDouble(),
        title: '${(count / moodProvider.moodHistory.length * 100).toStringAsFixed(1)}%',
        radius: 80,
        titleStyle: const TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.bold,
          color: Colors.white,
        ),
      );
    }).toList();
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '情绪分布',
          style: Theme.of(context).textTheme.titleLarge,
        ),
        const SizedBox(height: 16),
        SizedBox(
          height: 200,
          child: PieChart(
            PieChartData(
              sections: pieChartSections,
              centerSpaceRadius: 40,
              sectionsSpace: 2,
            ),
          ),
        ),
        const SizedBox(height: 16),
        // 图例
        Wrap(
          spacing: 16,
          runSpacing: 8,
          children: [1, 2, 3, 4, 5].map((moodType) {
            final color = AppColors.getMoodColor(moodType);
            final count = moodCounts[moodType] ?? 0;
            final percentage = moodProvider.moodHistory.isNotEmpty
                ? (count / moodProvider.moodHistory.length * 100).toStringAsFixed(1)
                : '0.0';
            
            return Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 16,
                  height: 16,
                  decoration: BoxDecoration(
                    color: color,
                    shape: BoxShape.circle,
                  ),
                ),
                const SizedBox(width: 4),
                Text(
                  '${_getMoodTypeName(moodType)}: $percentage%',
                  style: Theme.of(context).textTheme.bodySmall,
                ),
              ],
            );
          }).toList(),
        ),
      ],
    );
  }
  
  String _getMoodTypeName(int moodType) {
    switch (moodType) {
      case 1:
        return '很差';
      case 2:
        return '较差';
      case 3:
        return '一般';
      case 4:
        return '较好';
      case 5:
        return '很好';
      default:
        return '未知';
    }
  }
}